﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RadioStationService.cs" company="">
//   
// </copyright>
// <summary>
//   The radio station service.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace TinyRadio.UserInterface.Services
{
    using System.Collections.Generic;
    using System.Configuration;
    using System.Net;
    using System.Text;

    using Newtonsoft.Json;

    using TinyRadio.Models;

    /// <summary>The radio station service.</summary>
    public class RadioStationService : IRadioStationService
    {
        #region Public Methods and Operators

        /// <summary>The get radio stations.</summary>
        /// <returns>The <see cref="IEnumerable"/>.</returns>
        public IEnumerable<RadioStation> GetRadioStations()
        {
            try
            {
                using (var webClient = new WebClient { Encoding = Encoding.UTF8 })
                {
                    IWebProxy proxy = WebRequest.DefaultWebProxy;

                    if (proxy != null)
                    {
                        webClient.Proxy = WebRequest.DefaultWebProxy;
                        webClient.Credentials = CredentialCache.DefaultCredentials;
                        webClient.Proxy.Credentials = CredentialCache.DefaultCredentials;
                    }

                    string serviceUrl = string.Format("{0}/api/radiostations", ConfigurationManager.AppSettings["ServiceUrl"]);

                    string json = webClient.DownloadString(serviceUrl);

                    return JsonConvert.DeserializeObject<List<RadioStation>>(json);
                }
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }
}